package com.ruoyi.app.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import androidx.core.content.ContextCompat
import com.alick.learnwebrtc.manager.WebSocketManager
import com.bumptech.glide.Glide
import com.hjq.shape.view.ShapeButton
import com.ruoyi.app.R
import com.ruoyi.app.activity.LoginActivity
import com.ruoyi.app.activity.RegisterActivity
import com.ruoyi.app.activity.common.WebActivity
import com.ruoyi.app.api.ConfigApi
import com.ruoyi.app.model.Constant
import com.ruoyi.app.model.UserViewModel
import com.ruoyi.app.utils.CurrentInfo
import com.ruoyi.app.utils.LocalStorageUtils
import com.ruoyi.code.Frame
import com.ruoyi.code.base.activityViewModels
import com.ruoyi.code.utils.clickDelay
import com.tencent.mmkv.MMKV
import com.therouter.TheRouter
import com.xuexiang.xupdate.XUpdate

/**
 * 普通登录对应的Fragment
 */
class CommonLoginFragment : Fragment() {
    // 定义视图引用（可选：推荐使用 ViewBinding）
    private lateinit var etAccount: EditText
    private lateinit var etPassword: EditText
    private lateinit var etCode: EditText
    private lateinit var btnLogin: ShapeButton
    private lateinit var loginImg: ImageView
    private lateinit var llRegister: View

    private lateinit var tvPrivacy: View
    private lateinit var tvProtocol: View
    private lateinit var tvRegister: View



    private val viewModel: UserViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        // 加载布局
        val rootView = inflater.inflate(R.layout.common_login, container, false)
        // 初始化视图
        etAccount = rootView.findViewById(R.id.et_account)
        etPassword = rootView.findViewById(R.id.et_password)
        etCode = rootView.findViewById(R.id.et_code)
        btnLogin = rootView.findViewById(R.id.btn_login)
        loginImg = rootView.findViewById(R.id.logo_code_image)
        llRegister = rootView.findViewById(R.id.llRegister)
        tvProtocol = rootView.findViewById(R.id.tvProtocol)
        tvPrivacy = rootView.findViewById(R.id.tvPrivacy)
        tvRegister = rootView.findViewById(R.id.tvRegister)


        val currentContext = requireContext()

        tvRegister.clickDelay {
            RegisterActivity.startActivity(currentContext)
        }


        // 设置登录按钮点击事件
        btnLogin.clickDelay {
            // 处理登录逻辑
            viewModel.login(
                requireActivity(),
                etAccount.text.toString().trim(),
                etPassword.text.toString().trim(),
                etCode.text.toString().trim()
            )
        }

        viewModel.loginSuceess.observe(viewLifecycleOwner){ isSuccess ->
            if (isSuccess) {
                LocalStorageUtils.setUserName(etAccount.text.toString())
                if(!WebSocketManager.hasInit){
                    WebSocketManager.init(Constant.DEFAULT_INNER_ADDRESS, LocalStorageUtils.getUserName())
                }
                if(!WebSocketManager.webSocketClient.isOpen){
                    WebSocketManager.connect()
                }
                TheRouter.build(Constant.mainRoute)
                    .navigation()
                requireActivity().finish()
            } else {
                XUpdate.newBuild(requireActivity())
                    .promptThemeColor(ContextCompat.getColor(requireActivity(), R.color.red))
                    .updateUrl(ConfigApi.uploadApp)
                    .update()
            }
        }

        loginImg.clickDelay {
            viewModel.getVerificationCode()
        }

        viewModel.captchaEnabled.observe(viewLifecycleOwner) {
            if (it) {
                loginImg.visibility = View.VISIBLE
            } else {
                loginImg.visibility = View.GONE
            }
        }
        viewModel.imageCode.observe(viewLifecycleOwner) {
            Glide.with(Frame.getContext())
                .load("data:image/gif;base64,${it}")
                .into(loginImg)
        }

        viewModel.isRegister.observe(viewLifecycleOwner) {
            if (it) {
                llRegister.visibility = View.VISIBLE
            } else {
                llRegister.visibility = View.GONE
            }
        }
        return rootView
    }
}